//1.引入express mvc框架
const express = require("express");
const db = require("../modules/DBhelper");
const moment = require("moment")
//2. 创建保安大爷
let router = express.Router()

// add 加入购物车
router.post("/add", async function (request, response, next) {
    let cartObj = request.body;
    let sql = " SELECT* FROM `cart` WHERE `u_id`=? AND `c_name`=? ;";
    let parms = [
        cartObj.uId,
        cartObj.cname,
    ];

    let result = await db.exec(sql, parms);
    let isAddCart = result && result.length >= 1;//是否已经购买,true 购买

    if (isAddCart) { //修改数量和总金额

        let sqlUpdate = " UPDATE `cart` SET `c_num`= c_num+? , `c_total`=c_num*c_price WHERE `u_id`=? AND `c_name`=? ;";
        let pramsUpdate = [
            cartObj.cnum,
            cartObj.uId,
            cartObj.cname,
        ];

        let resultUpdate = await db.exec(sqlUpdate, pramsUpdate);
        let isUpdate = resultUpdate && resultUpdate.affectedRows >= 1//修改成功

        let updateMessage = {
            msg: isUpdate ? "加入购物车成功" : "加入购物车失败",
            status: isUpdate ? 200 : -200,
            model: "update"
        }
        response.json(updateMessage);

    } else {//第一次购买 
        let sqlInert = "INSERT INTO `cart` (`u_id`,`c_name`,`c_price`,`c_num`,`c_total`,`c_img`,`c_createtime`) "
        sqlInert += " VALUES(?,?,?,?,?,?,?);"
        let paramsInsert = [
            cartObj.uId,
            cartObj.cname,
            cartObj.cprice,
            cartObj.cnum,
            cartObj.cprice * cartObj.cnum,
            cartObj.cimg,
            moment().format("YYYY-MM-DD HH:mm:ss")
        ]

        let resultInsert = await db.exec(sqlInert, paramsInsert);

        let isInsert = resultInsert && resultInsert.affectedRows >= 1//修改成功

        let updateMessage = {
            msg: isInsert ? "加入购物车成功" : "加入购物车失败",
            status: isInsert ? 200 : -200,
            model: "insert"
        }
        response.json(updateMessage);
    }

})

//根据用户id查询购物车  KOA   ctx.request  ctx.response
router.get("/query", async function (request, response, next) {
    try {
        let userId = request.query.uId;
        let sql = " SELECT *FROM cart WHERE `u_id`=? AND `c_status`=1 ;"

        let resultQuery = await db.exec(sql, [userId]);

        response.json({ msg: "查询成功", status: 200, data: resultQuery })
    } catch (error) {
        response.json({ msg: "查询失败", status: -200, error })
    }
});

//修改购物里的数量
router.post("/modify", async function (request, response, next) {
    //购物车id, 数量
    let params = [
        request.body.cnum,
        request.body.cid
    ]
    console.log(params);
    let sql = "UPDATE `cart` SET `c_num`=? ,`c_total`=c_num*`c_price` WHERE `c_id`=? ;";
    let result = await db.exec(sql, params);
    let isModify = result && result.affectedRows >= 1; //修改成功

    console.log(isModify);
    response.json({ msg: isModify ? "修改成功" : "修改失败", status: isModify ? 200 : -200 })
})

router.post("/delete", async function (request, response, next) {
    try {
        let params = [
            request.body.cId
        ]
        //软删除,其实就是修改,不是物理删除(delete...)
        let sql = " UPDATE `cart` SET `c_status`=0 WHERE c_id=? ;";

        let result = await db.exec(sql, params)

        let isDelete = result && result.affectedRows >= 1;

        response.json({ msg: isDelete ? "删除成功" : "删除失败", status: isDelete ? 200 : -200 })
    } catch (error) {
        response.json({ msg: "删除失败", status: -200, error })
    }

})


//3.暴露保安大爷
module.exports = {
    router
}